from fitter import Fitter
from bfitter import BinnedFitter

import numpy

#class FitterExpo(Fitter):
    


class BinnedFitterExpo(BinnedFitter):
    fcn_latex = r'$A e^{-bx}$'
    fcn_str="{0}*math.exp(-{1}*x)"

    def __init__(self, data, par_names='$A$ $b$'.split()):
        super(BinnedFitterExpo, self).__init__(data, par_names, self.fcn_str)
        self._par_text_offset = 0.5

    def _set_initpars(self, frange):
        if not self.hist:
            raise FitException("BUG in expo.py. Need to set self.hist before calling _set_initpars.")

        bins = self.hist.bins() + 1

        lbins = numpy.log(bins)
        
        max_index = lbins.argmax()
        upper_limit_index = self.hist.bin_index(frange[1])

        if upper_limit_index < max_index:
            raise ValueError("Upper limit of fit range is less than the index of the maximum bin")

        min_index = lbins[max_index:upper_limit_index].argmin()

        xmax = self.hist.bin_center(max_index)
        xmin = self.hist.bin_center(min_index)

        ymax = lbins[max_index]
        ymin = lbins[min_index]

        slope = (ymax - ymin) / (xmax - xmin)

        return [bins[max_index], -slope]

    def _set_frange_none(self):
        bins = self.hist.bins()
        imax = bins.argmax()
        xmax = self.hist.bin_center(imax)
        xright = self.hist.bin_center(len(bins) - 1)
        
        return xmax, xright


        
        

